package Thread;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LianBao
 * Date: 2024-08-05
 * Time: 22:04
 */
public class MyBlockingQueue {
    private String[] data = null;
    private volatile int head = 0;//队头
    private volatile int tail = 0;//队尾
    private volatile int size = 0;//个数

    public MyBlockingQueue(int capacity) {
        data = new String[capacity];
    }

    public void put(String s) throws InterruptedException {
        synchronized (this) {
            if (size == data.length) {
                //队列满了,需要阻塞进入阻塞状态
                this.wait();
            }
            data[tail] = s;
            tail++;
            if (tail >= data.length) {
                tail = 0;
            }
            size++;
            this.notify();//put完毕,队列不为空,唤醒阻塞
        }
    }

    public String take() throws InterruptedException {
        String ret = "";
        synchronized (this) {
            if (size == 0) {
                //队列为空,需要进入阻塞状态
                this.wait();
            }
            ret = data[head];
            head++;
            if (head >= data.length) {
                head = 0;
            }
            size--;
            this.notify();//take完毕,队列不为满,唤醒阻塞
        }
        return ret;
    }
}
